package com.example.administrator.matriximage.viewpack;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;

import com.example.administrator.matriximage.uievent.InterEvent;
import com.example.administrator.matriximage.uievent.viewmsg.ViewMsg;

import org.greenrobot.eventbus.EventBus;

public class MatrixImage extends EventImage{


    public MatrixImage(Context context) {
        super(context);

    }

    public MatrixImage(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

    }

    public MatrixImage(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    public MatrixImage(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

    }



    /*
   * 检查矩阵，如果矩阵的缩放比例小于1.0恢复至原来的位置
   * */

    protected Matrix initMatrix=null;/*fitCenter第一次的设置矩阵是多少*/
    protected  Matrix imageMatrix=null;/*控制图形变化的矩阵*/
    protected  RectF imageRect;/*图像的原始区域*/
    protected RectF initRect=null;/*初始的图像区域*/

    /*重要继承方法，这个方法一定要继承*/
    protected void initImage() throws Exception //抛出异常，异常处理可以修复问题
    {
        Drawable drawable = getDrawable();
        Rect rect =   drawable.getBounds();
        imageRect=new RectF(rect.left,rect.top,rect.width(),rect.height());//图像原始的区域
        imageMatrix = getImageMatrix();
        initMatrix=new Matrix(imageMatrix);
        initRect=new RectF();
        initMatrix.mapRect(initRect);
        isFirst=false;
        /*下面可以初始化，缓存Bitmap，激光笔，遮罩灯，以及画笔*/


    }




    protected  Boolean isFirst=true;/*是否是第一次onDraw*/

    /*默认状态时只处理手势，要标记一下状态了*/

    @Override
    protected void onDraw(Canvas canvas) {

        if(isFirst) {
            super.onDraw(canvas);
            try {
                initImage();
                checkScale();
            }catch (Exception e)
            {
                android.util.Log.e(tag,e.toString());
            }

        }else {
            Bitmap bitmap = ((BitmapDrawable) getDrawable()).getBitmap();
            canvas.drawBitmap(bitmap, imageMatrix, null);

        }




    }





    private  RectF getImageRect() {

        RectF  matrixRect=new RectF();//图像所在屏幕的区域
        imageMatrix.mapRect(matrixRect,imageRect);

        return matrixRect;
    }


    private void checkTranslate()
    {
        RectF matrixRect=getImageRect();

           if(matrixRect.width()>=getWidth()) {

               if (matrixRect.left >= 0) {
                   imageMatrix.postTranslate(-matrixRect.left, 0);
               }

               if (matrixRect.right <=getWidth()) {
                   float disX = matrixRect.right - getWidth();
                   imageMatrix.postTranslate(-disX, 0);
               }

               if(matrixRect.height()<getHeight())
               {
                   imageMatrix.postTranslate(0, getHeight()/2-(matrixRect.top+matrixRect.bottom)/2);
                   return;
               }


           }

        if(matrixRect.height()>=getHeight()) {

            if (matrixRect.top >= 0) {
                imageMatrix.postTranslate(0, -matrixRect.top);

            }

            if (matrixRect.bottom <= getHeight()) {
                float disY = matrixRect.bottom - getHeight();
                imageMatrix.postTranslate(0, -disY);

            }
            if(matrixRect.width()<getWidth())
            {
                imageMatrix.postTranslate(getWidth()/2-(matrixRect.left+matrixRect.right)/2, 0);
                return ;
            }


        }


    }







    float lastX=0.0f;
    float lastY=0.0f;
    boolean canTranslate=false;/*是否可以执行，平移操作*/
    @Override
    public void downEvent(MotionEvent event) {
        lastX=event.getX();
        lastY=event.getY();
        canTranslate=true;
        invalidate();

    }

    @Override
    public void moveEvent(MotionEvent event) {
        if(!canTranslate)
            return;

         float nowX=event.getX();
         float nowY=event.getY();

         float distanceX= nowX-lastX;
         float distanceY=nowY-lastY;
         imageMatrix.postTranslate(distanceX,distanceY);
         checkTranslate();
         lastX=nowX;
         lastY=nowY;
         invalidate();
    }

    @Override
    public void upEvent(MotionEvent event) {
        if(!canTranslate)
            return;
        float nowX=event.getX();
        float nowY=event.getY();

        float distanceX= nowX-lastX;
        float distanceY=nowY-lastY;
        imageMatrix.postTranslate(distanceX,distanceY);
        checkTranslate();
        invalidate();

    }

    /*用来矩阵右乘*/
    float lastScale=1.0f;


    private void checkScale() {
        float[] imageMatrixValues=new float[9];
        imageMatrix.getValues(imageMatrixValues);
        float[] initMatrixValues=new float[9];
        initMatrix.getValues(initMatrixValues);

        if(imageMatrixValues[0]<=initMatrixValues[0]) {
            /*如果大小缩放没有什么变化，那么不变化*/
            /*消息拦截，让ViewPager处理Event*/
            imageMatrix = new Matrix(initMatrix);
            InterEvent interEvent=new InterEvent();
            interEvent.setIntercept(true);
            ViewMsg viewMsg=new ViewMsg();
            viewMsg.setObject(interEvent);
            EventBus.getDefault().post(viewMsg);

        }else
        {
            /*如果有变化刷新*/
            /*消息不拦截，让MatrixImage处理消息*/
            InterEvent interEvent=new InterEvent();
            interEvent.setIntercept(false);
            ViewMsg viewMsg=new ViewMsg();
            viewMsg.setObject(interEvent);

            EventBus.getDefault().post(viewMsg);


        }
        invalidate();
        checkTranslate();

    }

    @Override
    public void scaleBeginEvent(ScaleGestureDetector detector) {

        canTranslate=false;
        imageMatrix.postScale(detector.getScaleFactor()/lastScale,detector.getScaleFactor()/lastScale,detector.getFocusX(),detector.getFocusY());
        lastScale=detector.getScaleFactor();
        checkScale();
    }


    @Override
    public void scaleEvent(ScaleGestureDetector detector) {

        imageMatrix.postScale(detector.getScaleFactor()/lastScale,detector.getScaleFactor()/lastScale,detector.getFocusX(),detector.getFocusY());
        lastScale=detector.getScaleFactor();
        checkScale();
    }


    @Override
    public void scaleEndEvent(ScaleGestureDetector detector) {

        imageMatrix.postScale(detector.getScaleFactor()/lastScale,detector.getScaleFactor()/lastScale,detector.getFocusX(),detector.getFocusY());
        lastScale=1.0f;
        checkScale();

    }

    @Override
    public void revoke() {

    }







}
